//
//  FindViewController.m
//  Four_Fit
//
//  Created by xalo on 16/7/12.
//  Copyright © 2016年 xmaz. All rights reserved.
//


#import "FindViewController.h"
#import "FindModel.h"
#import "UrlManager.h"
#import "RecTableModel.h"
#import "RecScrollModel.h"
#import "RecommendCell.h"
#import "ScrollManager.h"
#import "EatModel.h"
#import "EatingCell.h"
#import "EatInfoViewController.h"
#import "insModel.h"
#import "CoreDataManager.h"
#import "DownLoadManager.h"
@interface FindViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,ScrManagerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *recommend;
@property (weak, nonatomic) IBOutlet UIButton *inspirational;
@property (weak, nonatomic) IBOutlet UIButton *eating;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (weak, nonatomic) IBOutlet UIView *underlineView;

@property (nonatomic,strong)UIView *signView;

@property (nonatomic,assign)BOOL animation;


@property (nonatomic,strong)UIScrollView *recommScrollview;
@property (nonatomic,strong)NSMutableArray *recommendArray;
@property (weak, nonatomic) IBOutlet UITableView *recommTableview;


@property (nonatomic,strong)NSMutableArray *recScrArray;

@property (nonatomic,strong)NSMutableArray *urlArr;///照片网址数组


@property (weak, nonatomic) IBOutlet UITableView *eatTableView;



@property (weak, nonatomic) IBOutlet UITableView *inspirationalTab;


@property (nonatomic,assign)NSInteger index;

@property (nonatomic,strong)NSMutableArray *dataSource;

@property (nonatomic,strong)NSString *filePath;

@end

@implementation FindViewController

- (NSString *)filePath{
    if (!_filePath) {
        _filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"FindImage"];
        
    }
    return _filePath;
}
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        [_dataSource addObject:[NSMutableArray array]];
        [_dataSource addObject:[NSMutableArray array]];
        [_dataSource addObject:[NSMutableArray array]];
        [_dataSource addObject:[NSMutableArray array]];
    }
    return _dataSource;
}


- (NSMutableArray *)urlArr{
    if (!_urlArr) {
        _urlArr = [NSMutableArray array];
    }
    return _urlArr;
}

- (NSMutableArray *)recommendArray{
    if (!_recommendArray) {
        _recommendArray = [NSMutableArray array];
    }
    return _recommendArray;
}

- (UIView *)signView{
    if (!_signView) {
        _signView = [[UIView alloc]init];
        _signView.size = CGSizeMake((kWidth-40)/3-20, 3);
        _signView.center = CGPointMake(self.recommend.center.x, -1);
        [self.underlineView addSubview:_signView];
        
    }
    return _signView;
    
}
- (UIScrollView *)recommScrollview{
    if (!_recommScrollview) {
        _recommScrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight/4)];
        _recommScrollview.contentSize = CGSizeMake(kWidth*self.recScrArray.count, kHeight/4);
        _recommScrollview.delegate = self;
        _recommScrollview.bounces = NO;
        _recommScrollview.bouncesZoom = NO;
       
        
    }
    return _recommScrollview;
}
- (void)viewDidLoad{
    [super viewDidLoad];
    
    if ([[NSFileManager defaultManager]fileExistsAtPath:self.filePath]) {
        [[NSFileManager defaultManager]createDirectoryAtPath:self.filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    self.title = @"发现";
    [self.recommTableview registerNib:[UINib nibWithNibName:@"RecommendCell" bundle:nil] forCellReuseIdentifier:@"recommend_cell"];
    [self.eatTableView registerNib:[UINib nibWithNibName:@"EatingCell" bundle:nil] forCellReuseIdentifier:@"eat_cell"];
    [self.inspirationalTab registerNib:[UINib nibWithNibName:@"EatingCell" bundle:nil] forCellReuseIdentifier:@"eat_cell"];
    
    self.recommTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.eatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    ///[self judegMentCoreDate];
    
   /// [self updateDataSourceWithIndex:0];
    
    ///[self updateDataSourceWithIndex:4];
    
   /// [self fetachRouceData];
    
}
- (void)judegMentCoreDate{
    
    
    if ([[CoreDataManager creatCoreDataManager]selectActionWithName:0].count!=0) {
        [[NSUserDefaults standardUserDefaults]setObject:@"y" forKey:@"recscr"];
    }else{
        [[NSUserDefaults standardUserDefaults]setObject:@"n" forKey:@"recscr"];
    }
    if ([[CoreDataManager creatCoreDataManager]selectActionWithName:1].count!=0) {
        [[NSUserDefaults standardUserDefaults]setObject:@"y" forKey:@"rectab"];
    }else{
        [[NSUserDefaults standardUserDefaults]setObject:@"n" forKey:@"rectab"];
    }
    if ([[CoreDataManager creatCoreDataManager]selectActionWithName:2].count!=0) {
        [[NSUserDefaults standardUserDefaults]setObject:@"y" forKey:@"eat"];
    }else{
        [[NSUserDefaults standardUserDefaults]setObject:@"n" forKey:@"eat"];
    }
    if ([[CoreDataManager creatCoreDataManager]selectActionWithName:3].count!=0) {
        [[NSUserDefaults standardUserDefaults]setObject:@"y" forKey:@"ins"];
    }else{
        [[NSUserDefaults standardUserDefaults]setObject:@"n" forKey:@"ins"];
    }
    
    
}
- (void)viewDidAppear:(BOOL)animated{
    self.signView.backgroundColor = [UIColor blueColor];
}
///刷新列表数据
- (void)updateDataSourceWithIndex:(NSInteger)index{
   
    ///刷新tecScr时，数据储存不为0
    if (index==0&&[[[NSUserDefaults standardUserDefaults] objectForKey:@"recscr"] isEqualToString:@"y"]) {
        
        self.dataSource[0] = [[CoreDataManager creatCoreDataManager]selectActionWithName:0];
        ScrollManager *manager = [[ScrollManager alloc]initWithFrame:CGRectMake(0, 0, kWidth, 200) imageArray:self.dataSource[0]];
       
        
        manager.managerDelegate = self;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
        [manager addGestureRecognizer:tap];
        manager.urlArray = self.recScrArray;
        self.recommTableview.tableHeaderView = manager;
        
        
        [self.recommTableview reloadData];
    }
    ///刷新1.2.3各自时，数据库数据不为0
    if ((index==1&&[[[NSUserDefaults standardUserDefaults] objectForKey:@"rectab"] isEqualToString:@"y"])||(index==2&&[[[NSUserDefaults standardUserDefaults] objectForKey:@"eat"] isEqualToString:@"y"])||(index==3&&[[[NSUserDefaults standardUserDefaults] objectForKey:@"ins"] isEqualToString:@"y"])) {
        
        self.dataSource[index] = [[CoreDataManager creatCoreDataManager]selectActionWithName:index];
        [self.eatTableView reloadData];
    }
    
    if (index==4&&[[[NSUserDefaults standardUserDefaults] objectForKey:@"recscr"] isEqualToString:@"y"]&&[[[NSUserDefaults standardUserDefaults] objectForKey:@"rectab"] isEqualToString:@"y"]&&[[[NSUserDefaults standardUserDefaults] objectForKey:@"eat"] isEqualToString:@"y"]&&[[[NSUserDefaults standardUserDefaults] objectForKey:@"ins"] isEqualToString:@"y"]) {
        
        for (NSInteger i=1; i<4; i++) {
            self.dataSource[i] = [[CoreDataManager creatCoreDataManager]selectActionWithName:i];
            [self.eatTableView reloadData];
        }
    }
    
    
}
///请求数据
- (void)fetachRouceData{
    
    ///饮食数据请求
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://api.fit-time.cn/ftinfo/refreshInfos?cat=1&page_size=20" parameters:@{} method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        [[CoreDataManager creatCoreDataManager]deleteDataWithIndex:2];
        NSDictionary *BigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        
        for (NSDictionary *smallDic in BigDic[@"infos"]) {
            EatModel *model = [[EatModel alloc]init];
            [model setValuesForKeysWithDictionary:smallDic];
            NSString *url = [@"http://ft-info.fit-time.cn/" stringByAppendingString:[model.photo substringFromIndex:8]];
            
           
 /**          Download *load = [[Download alloc]initWithUrl:[NSURL URLWithString:url]];
            [load startDownload];
            [load downloading:^(long long bytesWritten, float progress) {
                
            } didFinished:^(NSString *filePath, NSString *url) {
                model.photo = filePath;
                CoreDataManager *core = [[CoreDataManager alloc]init];
                [core addEatingTabWithModel:model];
            }];
    */
        }
        
    } updateUI:^{
        [self judegMentCoreDate];
        [self updateDataSourceWithIndex:2];
        
    }];
    /**
    ///励志数据请求
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://api.fit-time.cn/ftinfo/refreshInfos?cat=3&page_size=20" parameters:@{} method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
       /// NSLog(@"%@",bigDic);
        for (NSDictionary *smallDic in bigDic[@"infos"]) {
            insModel *model = [[insModel alloc]init];
            [model setValuesForKeysWithDictionary:smallDic];
            
            NSString *url = [@"http://ft-info.fit-time.cn/" stringByAppendingString:[model.photo substringFromIndex:8]];
            UIImageView *imageview = [[UIImageView alloc]init];
            [imageview sd_setImageWithPreviousCachedImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                NSData *imdata = UIImageJPEGRepresentation(imageview.image, 1.0f);
                model.photo = [imdata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
                [[CoreDataManager creatCoreDataManager]addInspirationalTabWithModel:model];
            }];
            
            
            ///[self.inspArr addObject:model];
        }
        
        
    } updateUI:^{
        [self judegMentCoreDate];
        [self updateDataSourceWithIndex:3];
        
    }];
    
    ///轮播图数据请求
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://api.fit-time.cn/ftinfo/listRecommends" parameters:@{} method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *scrDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",scrDic);
        for (NSDictionary *smallDic in scrDic[@"recommends"]) {
            RecScrollModel *model = [[RecScrollModel alloc]init];
            [model setValuesForKeysWithDictionary:smallDic];
            
            
            NSString *url = [@"http://ft-info.fit-time.cn/" stringByAppendingString:[model.photo substringFromIndex:8]];
            
            UIImageView *imageview = [[UIImageView alloc]init];
            [imageview sd_setImageWithPreviousCachedImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                 NSData *imdata = UIImageJPEGRepresentation(imageview.image, 1.0f);
                 model.photo = [imdata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
                 [[CoreDataManager creatCoreDataManager]addRecommendScrollPhotoWithModel:model];
            }];
           /// [imageview sd_setImageWithURL:[NSURL URLWithString:url]];
           
            
            
            
            
        }
        
    } updateUI:^{
        [self judegMentCoreDate];
        [self updateDataSourceWithIndex:0];
    }];
    
    
    
    
    ///一级数据请求
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://api.fit-time.cn/ftinfo/refreshInfoFeeds?page_size=20" parameters:@{} method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *smallDic in bigDic[@"infoFeeds"]) {
            FindModel *model = [[FindModel alloc]init];
            [model setValuesForKeysWithDictionary:smallDic];
            [self.recommendArray addObject:model];
        }
        
    } updateUI:^{
        
        ///推荐列表数据请求
        NSString *url = [[UrlManager creatUrlManager]packageURLWithNsArray:self.recommendArray andUrl:@"http://api.fit-time.cn/ftinfo/getInfoByIds?stat=1&"];
        [[QZRequestManager sharedManager] fetchDataWithUrl:url parameters:@{} method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
            
            NSDictionary *tableDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            ///NSLog(@"%@",tableDic);
            for (NSDictionary *smallDic in tableDic[@"infos"]) {
                RecTableModel *model = [[RecTableModel alloc]init];
                [model setValuesForKeysWithDictionary:smallDic];
                
                NSString *url = [@"http://ft-info.fit-time.cn/" stringByAppendingString:[model.photo substringFromIndex:8]];
                UIImageView *imageview = [[UIImageView alloc]init];
                [imageview sd_setImageWithPreviousCachedImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                    
                } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    NSData *imdata = UIImageJPEGRepresentation(imageview.image, 1.0f);
                    model.photo = [imdata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
                    [[CoreDataManager creatCoreDataManager]addRecommendTabWithModel:model];
                }];
                
                
                
            }
            
        } updateUI:^{
            [self judegMentCoreDate];
            [self updateDataSourceWithIndex:1];
        }];
        
    }];*/

}
- (void)pushNextViewWithIndex:(NSInteger)index{
    self.index = index;
}
- (void)tapAction{
    NSLog(@"%ld",self.index);
    
}

#pragma mark=============UITableViewDelegate================
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.recommTableview) {
        return [self.dataSource[1] count];
    }
    if (tableView == self.eatTableView) {
        return [self.dataSource[2] count];
    }
    if (tableView == self.inspirationalTab) {
        return [self.dataSource[3] count];
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView==self.eatTableView) {
        EatModel *model = self.dataSource[2][indexPath.row];
        EatingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"eat_cell" forIndexPath:indexPath];
        [cell setCellWithModel:model];
        return cell;
    }
    if (tableView == self.inspirationalTab) {
        
        insModel *model = self.dataSource[3][indexPath.row];
        EatingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"eat_cell" forIndexPath:indexPath];
        [cell setCellWithInsModel:model];
        
        return cell;
    }
    
    RecTableModel *model = self.dataSource[1][indexPath.row];
    RecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"recommend_cell" forIndexPath:indexPath];
    [cell setCellWithModel:model];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView==self.recommTableview) {
        return 200;
    }
    if (tableView == self.eatTableView||tableView == self.inspirationalTab) {
        return 150;
    }
    return 200;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.eatTableView) {
        EatModel *model = self.dataSource[2][indexPath.row];
        EatInfoViewController  *eat = [[EatInfoViewController alloc]init];
        eat.model = model;
        eat.url = model.url;
        [self.navigationController pushViewController:eat animated:YES];
    }
    if (tableView == self.inspirationalTab) {
        insModel *model = self.dataSource[3][indexPath.row];
        EatInfoViewController *ins = [[EatInfoViewController alloc]init];
        ins.url = model.url;
        [self.navigationController pushViewController:ins animated:YES];
    }
    if (tableView==self.recommTableview) {
        RecTableModel *model = self.dataSource[1][indexPath.row];
        EatInfoViewController *rec = [[EatInfoViewController alloc]init];
        rec.url = model.url;
        [self.navigationController pushViewController:rec animated:YES];
        
    }
    
}




#pragma mark==========ScrollViewDelegate设置===========
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[self.recommTableview class]]) {
         NSArray *visibleCells = [self.recommTableview visibleCells];
    for (RecommendCell *cell in visibleCells) {
        
        [cell cellOnTableView:self.recommTableview didScrollOnView:self.view];
    }
    }
    
    
    
    if ([scrollView isKindOfClass:[self.eatTableView class]]) {
        return;
    }
    
    
    CGPoint offset = scrollView.contentOffset;
    CGFloat percent = offset.x/(kWidth*2);
    
    ///判断是通过按钮还是scroll进行的滑动
    if (self.animation ) {
        [UIView animateWithDuration:0.5 animations:^{
            self.signView.centerX = self.recommend.centerX+(self.inspirational.centerX-self.recommend.centerX)*percent;
            self.animation = NO;
        }];
    }
    else{
        self.signView.centerX = self.recommend.centerX+(self.inspirational.centerX-self.recommend.centerX)*percent;
    }
    
   
    
    
    
}
- (IBAction)recommendAction:(UIButton *)sender {
    self.animation = YES;
    self.scrollview.contentOffset = CGPointMake(0, 0);
    
    
}
- (IBAction)eatingAction:(UIButton *)sender {
    self.animation = YES;
    self.scrollview.contentOffset = CGPointMake(kWidth, 0);
}
- (IBAction)inspirational:(UIButton *)sender {
    self.animation = YES;
    self.scrollview.contentOffset = CGPointMake(kWidth*2, 0);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
